package com.generic.ds;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class HibernateSession {

	private static final Log log = LogFactory.getLog(HibernateSession.class);
	private Session session = null;
	private Transaction transaction = null;

	public HibernateSession() {
		session = HibernateSessionFactory.getSessionFactory().openSession();
//		log.info("************* Session Created *************");
	}

	public Session getSession() {
		return session;
	}

	public void setSession(Session session) {
		this.session = session;
	}

	public void closeSession() {
		if (session != null) {
			session.close();
			session = null;
//			log.info("************* Session Closed *************");
		}
	}

	public void beginTransaction() {
		transaction = session.beginTransaction();
		log.info("************* Transaction Initiated *************");
	}

	public void commitTransaction() {
		if (transaction != null) {
			transaction.commit();
			log.info("************* Transaction Committed *************");
		}
	}

	public void rollbackTransaction() {
		rollbackTransaction(null);
	}
	
	public void rollbackTransaction(Exception e) {
		if(e != null) {
			log.error(e.getMessage());
		}
		
		if (transaction != null) {
			transaction.rollback();
		}
	}
}
